package per.wsj.httplib.ok

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import per.wsj.commonlib.utils.LogUtil
import java.util.concurrent.TimeUnit

object OkHttpUtils {

    // log interceptor
    private val mLoggingInterceptor: Interceptor by lazy { LoggingInterceptor() }

    val mClient: OkHttpClient by lazy { newClient() }

    private fun newClient(): OkHttpClient = OkHttpClient.Builder().apply {
        connectTimeout(15, TimeUnit.SECONDS)
        readTimeout(15, TimeUnit.SECONDS)
        eventListenerFactory(OkHttpEventListener.FACTORY)
        addInterceptor(mLoggingInterceptor)
    }.build()

    /**
     * 日志拦截器
     */
    private class LoggingInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val builder = StringBuilder()
            val startTime = System.nanoTime()
            val response: Response = with(chain.request()) {
                builder.append("\n" + method() + " " + url())
                // ...
                builder.append("\n").append(headers())
                chain.proceed(this)
            }
            builder.append("Received response in " + (System.nanoTime() - startTime) / 1e6 + "ms\n")
            builder.append("code:" + response.code() + "\n")
            LogUtil.d(builder.toString())
            return response
        }
    }
}